<template>
  <div class="login">
    <LoginLeftView></LoginLeftView>

    <div class="right-wrap">
      <!-- <div class="top-right-wrap">
        <div class="btn theme-btn" @click="toggleTheme">
          <i class="iconfont-sys">
            {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
          </i>
        </div>
        <ElDropdown @command="changeLanguage" popper-class="langDropDownStyle">
          <div class="btn language-btn">
            <i class="iconfont-sys icon-language">&#xe611;</i>
          </div>
          <template #dropdown>
            <ElDropdownMenu>
              <div v-for="lang in languageOptions" :key="lang.value" class="lang-btn-item">
                <ElDropdownItem :command="lang.value" :class="{ 'is-selected': locale === lang.value }">
                  <span class="menu-txt">{{ lang.label }}</span>
                  <i v-if="locale === lang.value" class="iconfont-sys icon-check">&#xe621;</i>
                </ElDropdownItem>
              </div>
            </ElDropdownMenu>
          </template>
</ElDropdown>
</div> -->
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <!-- <h3 class="title">{{ $t('login.title') }}</h3> -->
          <div class="form-item">
            <!-- <p class="sub-title">{{
              loginType === 'text' ? '请输入你的手机号和密码登录' : '请输入你的手机号和验证码登录'
            }}</p> -->
            <div style="display: flex;align-items: center;" @click="loginType = 'text'">
              <div v-if="loginType !== 'text'" class="back">
                <el-icon>
                  <ArrowLeftBold style="color: #000;" />
                </el-icon>
              </div>
              <p class="sub-title" :style="loginType === 'text' ? '' : 'cursor: pointer;'">{{
                loginType === 'text' ? '账号密码登录' : '手机验证码登录'
              }}</p>
            </div>
            <ElForm ref="formRef" :model="formData" :rules="rules" @keyup.enter="handleSubmit" style="margin-top: 25px">
              <div v-if="loginType === 'text'">
                <ElFormItem prop="username">
                  <ElInput :placeholder="$t('login.placeholder[0]')" size="large" v-model.trim="formData.username" />
                </ElFormItem>
                <ElFormItem prop="password">
                  <ElInput :placeholder="$t('login.placeholder[1]')" v-model.trim="formData.password" size="large"
                    :type="showPassword ? 'text' : 'password'" radius="8px" autocomplete="off">
                    <template #suffix>
                      <el-button @click="showPassword = !showPassword" type="text" style="padding: 0 6px;"
                        tabindex="-1">
                        <el-icon>
                          <template v-if="showPassword">
                            <View style="color: #606266;" />
                          </template>
                          <template v-else>
                            <Hide style="color: #606266;" />
                          </template>
                        </el-icon>
                      </el-button>
                    </template>
                  </ElInput>
                </ElFormItem>
              </div>

              <div v-if="loginType === 'phone'">
                <!-- <div v-if="websiteLoginType.includes('2')" class="back" @click="loginType = 'text'"><el-icon>
                    <Back />
                  </el-icon>返回</div> -->

                <ElFormItem prop="phone">
                  <ElInput :placeholder="$t('login.placeholder[0]')" size="large" v-model.trim="formData.phone" />
                </ElFormItem>
                <ElFormItem prop="code">
                  <el-row :gutter="12" style="width: 100%">
                    <el-col :span="countdown > 0 ? 17 : 18">
                      <ElInput v-model="formData.code" :placeholder="$t('login.placeholder[4]')" />
                    </el-col>
                    <el-col :span="countdown > 0 ? 7 : 6">
                      <el-button size="large" class="code" @click="sendSmsCodeData">
                        {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                      </el-button>
                    </el-col>
                  </el-row>
                </ElFormItem>
              </div>

              <div class="forget-password">
                <ElCheckbox v-model="formData.rememberPassword">{{
                  $t('login.rememberPwd')
                }}</ElCheckbox>
                <RouterLink :to="RoutesAlias.ForgetPassword">{{ $t('login.forgetPwd') }}</RouterLink>
              </div>

              <div class="btn-div">
                <el-checkbox v-model="agreeType" style="margin-right: 10px" @change="agreeTypeClick"></el-checkbox>
                我已阅读并同意<span class="color-green" @click="toPrivacy">《平台使用协议》</span>和<span class="color-green"
                  @click="toCharge">《隐私政策》</span>
              </div>
              <p class="titleHint" v-if="!agreeTypeDisplay">{{ $t('login.placeholder[3]') }}</p>

              <div style="margin-top: 30px">
                <ElButton class="login-btn" type="primary" size="large" @click="handleSubmit" :loading="loading"
                  v-ripple>
                  {{ $t('login.btnText') }}
                </ElButton>
              </div>

              <div class="footer" v-if="websiteRegisterConfigType === '1'">
                <p>
                  {{ $t('login.noAccount') }}
                  <RouterLink :to="RoutesAlias.Register">{{ $t('login.register') }}</RouterLink>
                </p>
              </div>
            </ElForm>
            <el-divider content-position="center"
              v-if="websiteLoginType.includes('2') || websiteLoginType.includes('3')">{{
                $t('login.other') }}</el-divider>

            <div class="other-login" v-if="websiteLoginType.includes('2') || websiteLoginType.includes('3')">
              <el-tooltip v-if="websiteLoginType.includes('2')" content="验证码登录" placement="bottom"
                effect="light"><el-icon :size="24" @click="loginType = 'phone'">
                  <Iphone />
                </el-icon></el-tooltip>
              <el-tooltip v-if="websiteLoginType.includes('3')" content="微信登录" placement="bottom" effect="light">
                <img class="el-icon" @click="getWXCaptcha" src="@/assets/img/wx.png"
                  style="width: 24px; height: 24px" />
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AppConfig from '@/config'
import { RoutesAlias } from '@/router/routesAlias'
import { ElMessage, ElNotification } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { LoginMethod } from '@/api/LoginMethod'
import { languageOptions } from '@/locales'
import { LanguageEnum, SystemThemeEnum } from '@/enums/appEnum'
import { useI18n } from 'vue-i18n'

defineOptions({ name: 'Login' })

const { t } = useI18n()
import { useSettingStore } from '@/store/modules/setting'
import type { FormInstance, FormRules } from 'element-plus'

const settingStore = useSettingStore()
const { isDark, systemThemeType } = storeToRefs(settingStore)

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const isPassing = ref(true)
const isClickPass = ref(false)
const countdown = ref(0)
const loginType = ref('text')
const websiteLoginType = ref('1')
const websiteRegisterConfigType = ref()

const systemName = AppConfig.systemInfo.name
const formRef = ref<FormInstance>()

const formData = reactive({
  // account: '',
  username: '',
  password: '',
  phone: '',
  code: '',
  rememberPassword: true
})

const showPassword = ref(false)

const canSend = computed(() => {
  return formData.phone && /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(formData.phone)
})

const validatePhone = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('login.rule[0]')))
  } else if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
    callback(new Error(t('login.rule[1]')))
  } else {
    callback()
  }
}

const rules = computed<FormRules>(() => ({
  username: [{ required: true, message: t('login.placeholder[0]'), trigger: 'blur' }],
  password: [{ required: true, message: t('login.placeholder[1]'), trigger: 'blur' }],
  phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
  code: [{ required: true, message: t('login.rule[2]'), trigger: 'blur' }]
}))

const loading = ref(false)

onMounted(() => {
  const code = route.query.code
  const state = route.query.state
  if (code && state) {
    wxLogin(code, state)
  }
  const accessToken = route.query.accessToken as string
  const refreshToken = route.query.refreshToken as string
  console.log(accessToken, refreshToken, "accessToken, refreshToken===");
  if (accessToken && refreshToken) {
    getThirdLogin(accessToken, refreshToken)
  }
  let infoData = JSON.parse(localStorage.getItem('lty-website-login-type') || '{}')
  websiteLoginType.value = infoData.loginConfig.loginWay
  websiteRegisterConfigType.value = infoData.registerConfig.registerWay
})

const getThirdLogin = async (accessToken: string, refreshToken: string) => {
  userStore.setToken(accessToken, refreshToken)
  const res = await UserService.getUserInfo()

  // 设置登录状态
  userStore.setLoginStatus(true)
  // 登录成功提示
  showLoginSuccessNotice()
  if (res.code === '00000') {
    userStore.setUserInfo(res.data)
    userStore.setLoginStatus(true)
    setTimeout(() => {
      window.location.href = 'https://www.lutongjiakao.com/admin/#/drivingSchoolConsole/schoolConsole'
    }, 300)
    console.log(router, "router===");
    console.log(route, "route===");

  } else {
    ElMessage.error(res.msg)
  }
}

const agreeType = ref(true)
const agreeTypeDisplay = ref(true)
const agreeTypeClick = async (e: any) => {
  agreeTypeDisplay.value = e
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!isPassing.value) {
        isClickPass.value = true
        return
      }

      if (!agreeType.value) {
        agreeTypeDisplay.value = false
        return
      } else {
        agreeTypeDisplay.value = true
      }

      if (loginType.value === 'text') {
        await handleAccountLogin()
      } else if (loginType.value === 'phone') {
        await handlePhoneLogin()
      }
    }
  })
}

// 登录成功提示
const showLoginSuccessNotice = () => {
  setTimeout(() => {
    ElNotification({
      title: t('login.success.title'),
      type: 'success',
      duration: 2500,
      zIndex: 10000,
      message: `${t('login.success.message')}, ${systemName}!`
    })
  }, 150)
}

async function sendSmsCodeData() {
  try {
    if (!formData.phone) {
      ElMessage.error('请输入手机号')
      return
    }
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    const paramsObj = {
      mobile: formData.phone,
      tempId: 2407768,
      type: 1
    }
    const { code, msg } = await LoginMethod.sendSmsCode(paramsObj)
    if (code === '00000') {
      await handleSubmit()
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
  } finally {
  }
}

async function getWXCaptcha() {
  try {
    const res = await LoginMethod.getWXQrCode({})
    if (res.code === '00000') {
      window.open(res.msg)
    }
  } catch {
  } finally {
  }
}

// 账号密码
async function handleAccountLogin() {
  loading.value = true
  const params = {
    username: formData.username,
    password: formData.password
  }
  try {
    const res = await UserService.login(params)

    if (res.code === '00000') {
      const { accessToken, refreshToken } = res.data

      if (accessToken) {
        userStore.setToken(accessToken, refreshToken)
        const res = await UserService.getUserInfo()

        // 设置登录状态
        userStore.setLoginStatus(true)
        // 登录成功提示
        showLoginSuccessNotice()

        if (res.code === '00000') {
          userStore.setUserInfo(res.data)
          userStore.setLoginStatus(true)
          router.push('/drivingSchoolConsole/schoolConsole')
        } else {
          ElMessage.error(res.msg)
        }
      }
    } else {
      loading.value = false
    }
  } finally {
    loading.value = false
  }
}

// 手机号登录
async function handlePhoneLogin() {
  try {
    loading.value = true
    const res = await LoginMethod.smsCodeLogin({
      mobile: formData.phone,
      code: formData.code
    })

    if (res.code === '00000') {
      const { accessToken, refreshToken } = res.data

      if (accessToken) {
        userStore.setToken(accessToken, refreshToken)
        const res = await UserService.getUserInfo()

        // 设置登录状态
        userStore.setLoginStatus(true)
        // 登录成功提示
        showLoginSuccessNotice()

        if (res.code === '00000') {
          userStore.setUserInfo(res.data)
          userStore.setLoginStatus(true)
          router.push('/drivingSchoolConsole/schoolConsole')
        } else {
          ElMessage.error(res.msg)
        }
      }
    } else {
      loading.value = false
    }
  } catch (err) {
  } finally {
    loading.value = false
  }
}

// 微信登录
async function wxLogin(code: any, state: any) {
  const res = await LoginMethod.wxScanCodeLogin({
    code,
    state
  })
  if (res.code === '00000') {
    const { accessToken, refreshToken } = res.data
    if (accessToken) {
      userStore.setToken(accessToken, refreshToken)
      const res = await UserService.getUserInfo()

      // 设置登录状态
      userStore.setLoginStatus(true)
      // 登录成功提示
      showLoginSuccessNotice()

      if (res.code === '00000') {
        userStore.setUserInfo(res.data)
        userStore.setLoginStatus(true)
        router.push('/drivingSchoolConsole/schoolConsole')
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      ElMessage.info('微信未绑定')
    }
  }
}

// 切换语言
const { locale } = useI18n()

const changeLanguage = (lang: LanguageEnum) => {
  if (locale.value === lang) return
  locale.value = lang
  userStore.setLanguage(lang)
}

// 切换主题
import { useTheme } from '@/composables/useTheme'
import { UserService } from '@/api/usersApi'

// 引入可见/隐藏图标
import { View, Hide } from '@element-plus/icons-vue'

const toggleTheme = () => {
  let { LIGHT, DARK } = SystemThemeEnum
  useTheme().switchThemeStyles(systemThemeType.value === LIGHT ? DARK : LIGHT)
}

const toPrivacy = () => {
  // 如果被路由守卫拦截，直接跳转到新页面
  const routeData = router.resolve({ name: 'PrivacyProtocol' })
  if (routeData) {
    window.open(routeData.href, '_blank')
  } else {
    // 路由守卫拦截时，手动拼接url跳转
    window.open('/termsConditions/privacy', '_blank')
  }
}
const toCharge = () => {
  // 如果被路由守卫拦截，直接跳转到新页面
  const routeData = router.resolve({ name: 'ChargeProtocol' })
  if (routeData) {
    window.open(routeData.href, '_blank')
  } else {
    // 路由守卫拦截时，手动拼接url跳转
    window.open('/termsConditions/charge', '_blank')
  }
}
</script>

<style lang="scss" scoped>
@use './index';

.btn-div {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.color-green {
  color: #8cd276;
  cursor: pointer;
}

.titleHint {
  font-size: 13px;
  color: #f56c6c;
  transform: translateY(-30px);
  /* 初始位置：向上偏移 30px（隐藏） */
  opacity: 0;
  /* 初始透明 */
  animation: slideDown 0.3s ease-in-out forwards;
  /* 动画：向下滑入 */
}

@keyframes slideDown {
  from {
    transform: translateY(-30px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    /* 滑到正常位置 */
    opacity: 1;
    /* 完全显示 */
  }
}
</style>
